<?php

namespace App\Models\User;

use App\Models\WxChat;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class WxUserStudentCertify extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'wx_user_student_certify';

    protected $primaryKey = 'user_id';
    public $incrementing = false;

    public function user()
    {
        return $this->hasOne(WxUser::class, 'id', 'user_id');
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // 在模型创建之前触发的操作
        });

        static::created(function ($model) {
            // 在模型创建之后触发的操作
            if($model->status == 1){
                WxUser::where('id', $model->user_id)->update(['university' => $model->school]);
                Cache::forget('get:cached:user:'.$model->user_id);
                GatewayUtils::success(GatewayUtils::uid2client_id($model->user_id), 12);
            }
        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'status'){
                    $originalValue = $original[$key] ?? 0;
                    if($value == 1){
                        if($originalValue == 0){
                            WxUser::where('id', $model->user_id)->update(['university' => $model->school]);
                            Cache::forget('get:cached:user:'.$model->user_id);
                            UserUtils::add_user_notice(4011, $model->user_id,'学生认证成功','您好，您申请的"'.$model->school.'"身份已认证成功',100);
                            GatewayUtils::success(GatewayUtils::uid2client_id($model->user_id), 12);
                        }
                    }else{
                        if($originalValue == 1){
                            WxUser::where('id', $model->user_id)->update(['university' => null]);
                            Cache::forget('get:cached:user:'.$model->user_id);
                            UserUtils::add_user_notice(4011, $model->user_id,'学生认证失败','您好，您申请的"'.$model->school.'"身份被驳回，可以联系平台客服咨询',100);
                            GatewayUtils::success(GatewayUtils::uid2client_id($model->user_id), 12);
                        }
                    }
                }
            }
        });
        static::deleted(function ($model) {
            WxChat::where('expand_type', 108)->where('expand_id', $model->id)->forceDelete();
        });
        // 其他的模型事件监听...
    }

}
